package com.jcfk.eam.service.mould;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.exception.CustomException;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.main.EamAssetInfoDao;
import com.jcfk.eam.dao.mould.EamMouldTaskInfoDao;
import com.jcfk.eam.domain.dto.main.EamAssetInfoDTO;
import com.jcfk.eam.domain.dto.main.EamPointCheckDetailDTO;
import com.jcfk.eam.domain.dto.main.EamPointCheckOrderDTO;
import com.jcfk.eam.domain.dto.mould.EamMouldTaskInfoDTO;
import com.jcfk.eam.domain.dto.mould.EamMouldTaskInfoDetailDTO;
import com.jcfk.eam.domain.po.base.EamLocationInfo;
import com.jcfk.eam.domain.po.base.EamRepairOrder;
import com.jcfk.eam.domain.po.base.EamRepairOrderPointDetail;
import com.jcfk.eam.domain.po.main.EamAssetInfo;
import com.jcfk.eam.domain.po.mould.EamMouldOutinboundRecord;
import com.jcfk.eam.domain.po.mould.EamMouldTaskInfo;
import com.jcfk.eam.domain.po.mould.EamMouldTaskInfoDetail;
import com.jcfk.eam.domain.query.main.EamPointCheckDetailQuery;
import com.jcfk.eam.domain.query.main.EamPointCheckOrderQuery;
import com.jcfk.eam.domain.query.mould.EamMouldTaskInfoQuery;
import com.jcfk.eam.enums.MouldPackageRecordStatusEnum;
import com.jcfk.eam.service.base.EamLocationInfoService;
import com.jcfk.eam.service.base.EamRepairOrderPointDetailService;
import com.jcfk.eam.service.main.EamAssetInfoService;
import com.jcfk.eam.service.main.EamPointCheckDetailService;
import com.jcfk.eam.service.main.EamPointCheckOrderService;
import com.jcfk.eam.service.main.EamRepairOrderService;
import com.jcfk.eam.util.time.LocalDateTimeUtil;
import com.jcfk.system.api.utils.CodeBuildUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 模具任务表
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2025-07-17
 */
@Service
public class EamMouldTaskInfoService extends BaseService<EamMouldTaskInfoDao, EamMouldTaskInfo> {


    @Autowired
    private EamMouldTaskInfoDetailService eamMouldTaskInfoDetailService;
    @Autowired
    private EamAssetInfoService eamAssetInfoService;
    @Autowired
    private EamMouldWorkRecordService eamMouldWorkRecordService;
    @Autowired
    private EamLocationInfoService eamLocationInfoService;
    @Autowired
    private MouldAssetInfoService mouldAssetInfoService;
    @Autowired
    private EamMouldOutinboundRecordService eamMouldOutinboundRecordService;
    @Autowired
    private EamAssetInfoDao eamAssetInfoDao;
    @Autowired
    private EamRepairOrderService eamRepairOrderService;
    @Autowired
    private EamRepairOrderPointDetailService eamRepairOrderPointDetailService;
    @Autowired
    private EamPointCheckOrderService eamPointCheckOrderService;
    @Autowired
    private EamPointCheckDetailService eamPointCheckDetailService;
    @Autowired
    private EamMouldPackageRecordService eamMouldPackageRecordService;

    /**
     * EamMouldTaskInfo分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamMouldTaskInfoDTO> queryByPage(DataPage<EamMouldTaskInfoDTO> page, EamMouldTaskInfoQuery query) {
        // 分页查询
        query.setMaterialCode(StringUtils.isEmpty(query.getMaterialCode()) ? query.getMaterialCode() : query.getMaterialCode() + "%");
        query.setMaterialName(StringUtils.isEmpty(query.getMaterialName()) ? query.getMaterialName() : query.getMaterialName() + "%");
        query.setEquipName(StringUtils.isEmpty(query.getEquipName()) ? query.getEquipName() : query.getEquipName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamMouldTaskInfoDTO>
     */
    public List<EamMouldTaskInfoDTO> getList(EamMouldTaskInfoQuery query) {
        // 查询条件
        QueryWrapper<EamMouldTaskInfo> qw = new QueryWrapper<>();
        qw.lambda().like(!StrUtil.isEmpty(query.getMaterialCode()), EamMouldTaskInfo::getMaterialCode, query.getMaterialCode());
        qw.lambda().like(!StrUtil.isEmpty(query.getMaterialName()), EamMouldTaskInfo::getMaterialName, query.getMaterialName());
        qw.lambda().like(!StrUtil.isEmpty(query.getEquipName()), EamMouldTaskInfo::getEquipName, query.getEquipName());
        qw.lambda().ge(!StrUtil.isEmpty(query.getPlanDateStart()), EamMouldTaskInfo::getPlanDate, query.getPlanDateStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getPlanDateEnd()), EamMouldTaskInfo::getPlanDate, query.getPlanDateEnd());
        qw.lambda().eq((query.getTaskStatus() != null), EamMouldTaskInfo::getTaskStatus, query.getTaskStatus());
        if (query.getPlanDate() != null) {
            qw.lambda().ge(EamMouldTaskInfo::getPlanDate, query.getPlanDate());
            LocalDateTime plandate = LocalDateTimeUtil.dateToLocalDateTime(query.getPlanDate());
            LocalDateTime nextdate = plandate.plusDays(1);
            Date planDateEnd = LocalDateTimeUtil.localDateTimeToDate(nextdate);
            qw.lambda().lt(EamMouldTaskInfo::getPlanDate, planDateEnd);
        }
        // 查询数据
        List<EamMouldTaskInfo> list = super.list(qw);

        return convertList(list, EamMouldTaskInfoDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<EamMouldTaskInfoDTO>
     */
    public List<EamMouldTaskInfoDetailDTO> getDetails(EamMouldTaskInfoQuery query) {
        // 查询条件
        QueryWrapper<EamMouldTaskInfoDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), EamMouldTaskInfoDetail::getTaskId, query.getId());
        qw.lambda().eq(query.getPassStatus() != null, EamMouldTaskInfoDetail::getPassStatus, query.getPassStatus());
        qw.lambda().eq(query.getOutboundStatus() != null, EamMouldTaskInfoDetail::getOutboundStatus, query.getOutboundStatus());
        qw.lambda().eq(EamMouldTaskInfoDetail::getDeleted, 0);

        // 查询数据
        List<EamMouldTaskInfoDetail> list = eamMouldTaskInfoDetailService.list(qw);

        return convertList(list, EamMouldTaskInfoDetailDTO.class);
    }


    /**
     * 判断EamMouldTaskInfo是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamMouldTaskInfoDTO dto) {
        if (StrUtil.isEmpty(dto.getEquipName())) return RetResult.fail("生产批次号不能为空");
        if (dto.getProcessesClassification() != null) return RetResult.fail("工序分类不能为空");
        if (StrUtil.isEmpty(dto.getProcessingOrderNumber())) return RetResult.fail("任务编号不能为空");
        if (StrUtil.isEmpty(dto.getMaterialCode())) return RetResult.fail("成品物料号不能为空");
        if (StrUtil.isEmpty(dto.getMaterialName())) return RetResult.fail("成品物料名不能为空");
        if (null == dto.getPlanDate()) return RetResult.fail("计划日期不能为空");
        if (null == dto.getPlanQuantity()) return RetResult.fail("计划数量不能为空");
        if (null == dto.getMouldQuantity()) return RetResult.fail("模数不能为空");
        EamAssetInfoDTO eamAssetInfoDTO = new EamAssetInfoDTO();
        eamAssetInfoDTO.setProductCode(dto.getMaterialCode());
        eamAssetInfoDTO.setProcess(dto.getProcessesClassification());
        List<EamAssetInfoDTO> eamAssetInfoList = eamAssetInfoService.queryProductMould(eamAssetInfoDTO);
        if (eamAssetInfoList.isEmpty()) return RetResult.fail("不存在此工序物料的模具");
        Optional<EamAssetInfoDTO> eamAssetInfoDTOOptional = eamAssetInfoList.stream().filter(item -> {
            return item.getEnabled() == null || item.getEnabled() != 1;
        }).findFirst();
        if (eamAssetInfoDTOOptional.isPresent()) {
            return RetResult.fail(String.format("存在未启用的模具:%s", eamAssetInfoDTOOptional.get().getAssetCode()));
        }
        Optional<EamAssetInfoDTO> assetInfoDTOOptional = eamAssetInfoList.stream().filter(item -> {
            return item.getAssetStatus() == 2;
        }).findFirst();
        if (assetInfoDTOOptional.isPresent()) {
            return RetResult.fail(String.format("存在未维修的模具:%s", assetInfoDTOOptional.get().getAssetCode()));
        }
        return RetResult.ok();
    }

    /**
     * 插入模具任务表
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamMouldTaskInfoDTO dto) {

        // 保存
        EamMouldTaskInfo item = new EamMouldTaskInfo();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 保存明细表
        // eamMouldTaskInfoDetailService.saveBatch(dto.getDetails(),item.getId());
    }


    /**
     * 更新模具任务表
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamMouldTaskInfoDTO dto) {

        // 保存
        EamMouldTaskInfo item = new EamMouldTaskInfo();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (EamMouldTaskInfoDetailDTO detail : dto.getDetails()) {
            detail.setTaskId(item.getId());
        }
        // 保存明细表
        // eamMouldTaskInfoDetailService.saveBatch(dto.getDetails(),item.getId());
    }


    /**
     * 根据批量主键删除模具任务表(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamMouldTaskInfoDTO dto) {

        EamMouldTaskInfo item = new EamMouldTaskInfo();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamMouldTaskInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeletePlan(EamMouldTaskInfoDTO dto) {

        EamMouldTaskInfo item = new EamMouldTaskInfo();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamMouldTaskInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_id", dto.getPlanId());

        return this.update(item, queryWrapper);
    }


    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamMouldTaskInfo item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }


    /**
     * 根据主键获取模具任务表信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamMouldTaskInfoDTO get(String id) {
        // 查询数据
        EamMouldTaskInfo item = this.baseMapper.selectById(id);
        EamMouldTaskInfoDTO dto = new EamMouldTaskInfoDTO();
        try {

            BeanUtils.copyProperties(item, dto);
            List<EamAssetInfoDTO> eamAssetInfoDTOList = eamAssetInfoDao.queryByMaterialCode(dto, new ArrayList<>());
            dto.setAssetList(eamAssetInfoDTOList);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }


    /**
     * 根据主键获取模具任务表信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamMouldTaskInfo item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }

    /**
     * 检测模具入库校验
     *
     * @param EamMouldTaskInfoDTO
     * @return
     */
    public boolean checkMouldSave(EamMouldTaskInfoDTO EamMouldTaskInfoDTO) {
        List<EamAssetInfoDTO> eamAssetInfoDTOList = eamAssetInfoDao.queryByTaskId(EamMouldTaskInfoDTO.getId());
        //只有正常/生产/启用/在库的模具才可以出库
        return eamAssetInfoDTOList.stream().allMatch(item -> {
            return (item.getAssetStatus() == 3 || item.getAssetStatus() == 1)
                    && item.getStorageStatus() == 1
                    && item.getEnabled() != null && item.getEnabled() == 1;
        });
    }

    /**
     * 模具出库提交
     *
     * @param eamMouldTaskInfoDTO
     * @return
     */
    @Transactional
    public int mouldSave(EamMouldTaskInfoDTO eamMouldTaskInfoDTO) {
        // TODO: 2025/7/31 出库保存提交
        EamLocationInfo eamLocationInfo = eamLocationInfoService.getById(eamMouldTaskInfoDTO.getLocationId());
        if (eamLocationInfo == null) {
            return 1;
        }
        // 改变主表状态
        EamMouldTaskInfo eamMouldTaskInfo = getById(eamMouldTaskInfoDTO.getId());
        this.setDefaultValue(eamMouldTaskInfo);
        eamMouldTaskInfo.setTaskStatus(1);
        eamMouldTaskInfo.setLocationId(eamMouldTaskInfoDTO.getLocationId());
        eamMouldTaskInfo.setLocationName(eamLocationInfo.getLocationName());

        // 改变模具台账
        QueryWrapper<EamMouldTaskInfoDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamMouldTaskInfoDetail::getTaskId, eamMouldTaskInfoDTO.getId());
        queryWrapper.lambda().eq(EamMouldTaskInfoDetail::getDeleted, 0);
        List<EamMouldTaskInfoDetail> detailList = eamMouldTaskInfoDetailService.list(queryWrapper);
        // 保存任务详情为出库状态
        for (EamMouldTaskInfoDetail detail : detailList) {
            detail.setOutboundStatus(1);
            detail.setLocationId(eamMouldTaskInfoDTO.getLocationId());
            detail.setLocationName(eamLocationInfo.getLocationName());
            detail.setOutboundTime(new Date());
        }
        eamMouldTaskInfoDetailService.updateBigBatch(detailList);
        Long passCount = detailList.stream().filter(item -> 1 == item.getPassStatus()).count();
        eamMouldTaskInfo.setOutboundQuantity(detailList.size());
        eamMouldTaskInfo.setPassQuantity(passCount.toString());
        this.updateById(eamMouldTaskInfo);
        List<String> mouldCodes = detailList.stream().map(EamMouldTaskInfoDetail::getMouldCode).collect(Collectors.toList());
        EamAssetInfo EamAssetInfo = new EamAssetInfo();
        EamAssetInfo.setLocationId(eamMouldTaskInfoDTO.getLocationId());
        EamAssetInfo.setLocationName(eamMouldTaskInfoDTO.getLocationName());
        EamAssetInfo.setAssetStatus(1);
        EamAssetInfo.setStorageStatus(0);
        eamAssetInfoService.updateBatch(mouldCodes, EamAssetInfo);
        // 改变增加操作记录
        eamMouldWorkRecordService.insertBatch(mouldCodes, 2, eamMouldTaskInfo);
        // 创建出库记录
        eamMouldTaskInfoDTO.setLocationName(eamLocationInfo.getLocationName());
        eamMouldOutinboundRecordService.insertBatch(detailList, 2, eamMouldTaskInfoDTO);
        //创建模具框记录
        eamMouldPackageRecordService.insertBatch(detailList, MouldPackageRecordStatusEnum.OUTBOUND, eamMouldTaskInfo);
        return 1;
    }

    /**
     * 检测模具入库校验
     *
     * @param dto
     * @return
     */
    public boolean checkMouldSaveStore(EamAssetInfoDTO dto) {
        EamAssetInfo eamAssetInfo = eamAssetInfoService.getById(dto.getId());
        //不在库才能出库
        return eamAssetInfo != null && (eamAssetInfo.getStorageStatus() == 0);
    }

    /**
     * 模具入库提交
     *
     * @param dto
     * @return
     */
    @Transactional
    public int mouldSaveStore(EamAssetInfoDTO dto) {
        // TODO: 2025/8/1 入库保存
        String planId = null;
        Integer submitStatus = 0;
        QueryWrapper<EamMouldOutinboundRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EamMouldOutinboundRecord::getDeleted, 0);
        queryWrapper.lambda().eq(EamMouldOutinboundRecord::getMouldCode, dto.getAssetCode());
        queryWrapper.lambda().eq(EamMouldOutinboundRecord::getSubmitStatus, 0);
        queryWrapper.lambda().orderByDesc(EamMouldOutinboundRecord::getOutinboundTime);
        List<EamMouldOutinboundRecord> findRecordList = eamMouldOutinboundRecordService.list(queryWrapper);
        if (findRecordList.size() > 0) {
            planId = findRecordList.get(0).getId();
        } else {
            planId = UUID.randomUUID().toString().replace("-", "");
        }
        if (0 != dto.getAssetStatus()) {
            // 提交
            submitStatus = 1;
        }
        // 根据状态保存点检信息
        mouldAssetInfoService.saveSpotCheckIn(dto, planId);
        // 保存入库记录
        if (findRecordList.size() > 0) {
            EamMouldOutinboundRecord updateRecord = findRecordList.get(0);
            updateRecord.setLocationId(dto.getLocationId());
            updateRecord.setLocationName(dto.getLocationName());
            updateRecord.setOutinboundTime(new Date());
            updateRecord.setOutinboundType(1);
            updateRecord.setPassStatus(dto.getPassStatus());
            updateRecord.setSubmitStatus(submitStatus);
            eamMouldOutinboundRecordService.setDefaultValue(updateRecord);
            eamMouldOutinboundRecordService.updateById(updateRecord);
        } else {
            EamMouldOutinboundRecord eamMouldOutinboundRecord = new EamMouldOutinboundRecord();
            eamMouldOutinboundRecord.setMouldCode(dto.getAssetCode());
            eamMouldOutinboundRecord.setMouldName(dto.getAssetName());
            eamMouldOutinboundRecord.setMouldType(dto.getAssetTypeCode());
            eamMouldOutinboundRecord.setLocationId(dto.getLocationId());
            eamMouldOutinboundRecord.setLocationName(dto.getLocationName());
            eamMouldOutinboundRecord.setOutinboundTime(new Date());
            eamMouldOutinboundRecord.setOutinboundType(1);
            eamMouldOutinboundRecord.setPassStatus(dto.getPassStatus());
            eamMouldOutinboundRecord.setSubmitStatus(submitStatus);
            eamMouldOutinboundRecordService.setDefaultValue(eamMouldOutinboundRecord);
            eamMouldOutinboundRecord.setId(planId);
            eamMouldOutinboundRecordService.save(eamMouldOutinboundRecord);
        }
        if (0 != dto.getAssetStatus()) {
            // 保存台账
            List<String> mouldCodes = new ArrayList<>();
            mouldCodes.add(dto.getAssetCode());
            EamAssetInfo EamAssetInfo = new EamAssetInfo();
            EamAssetInfo.setLocationId(dto.getLocationId());
            EamAssetInfo.setLocationName(dto.getLocationName());
            EamAssetInfo.setAssetStatus(dto.getAssetStatus());
            EamAssetInfo.setStorageStatus(1);
            eamAssetInfoService.updateBatch(mouldCodes, EamAssetInfo);
            // 改变增加操作记录
            eamMouldWorkRecordService.insertBatch(mouldCodes, 1);
            //维修状态改变增加操作记录
            if (dto.getAssetStatus() == 2) {
                eamMouldWorkRecordService.insertBatch(mouldCodes, 9);
                createEamRepairOrder(dto);
            }
        }
        return 1;
    }

    /**
     * 生成入库故障报修单
     *
     * @param dto
     */
    public void createEamRepairOrder(EamAssetInfoDTO dto) {
        if (!dto.getListCheckOrder().isEmpty()) {
            for (EamPointCheckOrderDTO eamPointCheckOrderDTO : dto.getListCheckOrder()) {
                List<EamPointCheckDetailDTO> eamPointCheckDetailDTOS = eamPointCheckOrderDTO.getDetails();
                if (!eamPointCheckDetailDTOS.isEmpty() && eamPointCheckDetailDTOS.stream().anyMatch(item -> {
                    //存在不合格点检项
                    return "0".equals(item.getSopItemResult());
                })) {
                    createEamRepairOrder(null, eamPointCheckOrderDTO, eamPointCheckOrderDTO.getDetails(), "入库维修报修单");
                }
            }
        }
    }

    /**
     * 出库维修接口服务
     *
     * @param eamMouldTaskInfoDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void mouldSaveMaintenance(EamMouldTaskInfoDTO eamMouldTaskInfoDTO) {
        EamMouldTaskInfo eamMouldTaskInfo = this.getById(eamMouldTaskInfoDTO.getId());
        if (eamMouldTaskInfo.getTaskStatus() != 0) {
            throw new CustomException("模具任务版本变更，请重新查询任务列表");
        }
        QueryWrapper<EamMouldTaskInfoDetail> eamMouldTaskInfoDetailQueryWrapper = new QueryWrapper<>();
        eamMouldTaskInfoDetailQueryWrapper.lambda().eq(EamMouldTaskInfoDetail::getDeleted, 0);
        eamMouldTaskInfoDetailQueryWrapper.lambda().eq(EamMouldTaskInfoDetail::getTaskId, eamMouldTaskInfo.getId());
        List<EamMouldTaskInfoDetail> eamMouldTaskInfoDetailList = eamMouldTaskInfoDetailService.list(eamMouldTaskInfoDetailQueryWrapper);
        //不合格模具
        List<EamMouldTaskInfoDetail> noPassTaskDetailList = eamMouldTaskInfoDetailList.stream().filter(item -> {
            return item.getPassStatus() != null && item.getPassStatus() == 0;
        }).collect(Collectors.toList());
        List<String> mouldCodes = new ArrayList<>();
        for (EamMouldTaskInfoDetail eamMouldTaskInfoDetail : noPassTaskDetailList) {
            QueryWrapper<EamAssetInfo> eamAssetInfoQueryWrapper = new QueryWrapper<>();
            eamAssetInfoQueryWrapper.lambda().eq(EamAssetInfo::getDeleted, 0);
            eamAssetInfoQueryWrapper.lambda().eq(EamAssetInfo::getAssetKind, 3);
            eamAssetInfoQueryWrapper.lambda().eq(EamAssetInfo::getAssetCode, eamMouldTaskInfoDetail.getMouldCode());
            EamAssetInfo eamAssetInfo = eamAssetInfoService.getOne(eamAssetInfoQueryWrapper);
            if (eamAssetInfoService == null || eamAssetInfo.getAssetStatus() != 3) {
                throw new CustomException("存在非正常状态模具，请检查模具状态后重试");
            }
            eamAssetInfoService.setDefaultValue(eamAssetInfo);
            eamAssetInfo.setAssetStatus(2);
            if (!eamAssetInfoService.updateById(eamAssetInfo)) {
                throw new CustomException("模具版本变更，请重试");
            }
            mouldCodes.add(eamMouldTaskInfoDetail.getMouldCode());
            EamPointCheckOrderQuery eamPointCheckOrderQuery = new EamPointCheckOrderQuery();
            eamPointCheckOrderQuery.setDeleted(0);
            eamPointCheckOrderQuery.setPlanId(eamMouldTaskInfoDetail.getId());
            List<EamPointCheckOrderDTO> eamPointCheckOrderList = eamPointCheckOrderService.getList(eamPointCheckOrderQuery);
            for (EamPointCheckOrderDTO eamPointCheckOrder : eamPointCheckOrderList) {
                EamPointCheckDetailQuery query = new EamPointCheckDetailQuery();
                query.setOrderId(eamPointCheckOrder.getId());
                List<EamPointCheckDetailDTO> eamPointCheckDetailList = eamPointCheckDetailService.getList(query);
                createEamRepairOrder(eamMouldTaskInfo.getId(), eamPointCheckOrder, eamPointCheckDetailList, "出库维修报修单");
            }
        }
        if (!mouldCodes.isEmpty()) {
            //更新任务到维修状态
            eamMouldTaskInfo.setTaskStatus(2);
            this.updateById(eamMouldTaskInfo);
            eamMouldWorkRecordService.insertBatch(mouldCodes, 9);
        }
    }


    /**
     * 生成故障报修单
     *
     * @param eamPointCheckOrder
     * @param eamPointCheckDetailList
     * @param remarks
     */
    public void createEamRepairOrder(String taskId, EamPointCheckOrderDTO eamPointCheckOrder, List<EamPointCheckDetailDTO> eamPointCheckDetailList, String remarks) {
        EamRepairOrder eamRepairOrder = new EamRepairOrder();
        eamRepairOrderService.setDefaultValue(eamRepairOrder);
        eamRepairOrder.setId(IdUtils.newId());
        eamRepairOrder.setTaskId(taskId);
        eamRepairOrder.setAssetKind(3);
        eamRepairOrder.setAssetId(eamPointCheckOrder.getAssetId());
        eamRepairOrder.setRepairTime(new Date());
        eamRepairOrder.setRepairUser(SecurityUtils.getUserId());
        eamRepairOrder.setRepairUserName(SecurityUtils.getUserName());
        eamRepairOrder.setFaultStatus("2");
        eamRepairOrder.setRepairLevel("2");
        eamRepairOrder.setRemarks(remarks);
        eamRepairOrder.setRepairSource("1");
        eamRepairOrder.setRepairStatus("0");
        eamRepairOrder.setRepairCode(CodeBuildUtils.buildCode("eam_bx", ""));
        List<EamRepairOrderPointDetail> details = eamPointCheckDetailList.stream().map(item -> {
            EamRepairOrderPointDetail eamRepairOrderPointDetail = new EamRepairOrderPointDetail();
            eamRepairOrderPointDetailService.setDefaultValue(eamRepairOrderPointDetail);
            eamRepairOrderPointDetail.setRepairOrderId(eamRepairOrder.getId());
            eamRepairOrderPointDetail.setSopItemId(item.getSopItemId());
            eamRepairOrderPointDetail.setSopItemName(item.getSopItemName());
            eamRepairOrderPointDetail.setSopItemResult(item.getSopItemResult());
            eamRepairOrderPointDetail.setSopItemValue(item.getSopItemValue());
            eamRepairOrderPointDetail.setRemarks(remarks);
            return eamRepairOrderPointDetail;
        }).collect(Collectors.toList());
        eamRepairOrderService.save(eamRepairOrder);
        if (!details.isEmpty()) {
            eamRepairOrderPointDetailService.saveBatch(details);
        }
    }
}

